package org.amos.server.tool.log;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.constant.SystemConstant;
import org.amos.core.basic.utils.HttpUtils;
import org.amos.core.basic.utils.JsonUtils;
import org.amos.core.frame.aspect.AopManager;
import org.amos.core.frame.utils.ReflectUtils;
import org.amos.server.modules.upms.entity.Log;
import org.amos.server.modules.upms.service.ILogLoginService;
import org.slf4j.MDC;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @desc: 自定义日志处理类
 * 开启方式：1、amos.log.show-default-log=true，2、实现AopManager
 * @author: liubt
 * @date: 2022-08-11 16:21
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class AopLogManager implements AopManager {
    private final ILogLoginService logService;
    @Override
    public void doCustom(org.amos.core.basic.annotation.Log log, Class<?> clazz, Method method, Object[] args, String resultInfo, String level, Long time) throws Exception {
        String ip = HttpUtils.getIp();
        String url = HttpUtils.getURI();
        String clazzName = clazz.getName();
        String methodName = method.getName();
        String traceId = MDC.get(SystemConstant.TRACE_ID);
        String params = JsonUtils.objectToJson(ReflectUtils.getParamsMap(method, args));

        Log logLogin = new Log();
        logLogin.setClazz(clazzName);
        logLogin.setIp(ip);
        logLogin.setName(log.value());
        logLogin.setLevel(level);
        logLogin.setParams(params);
        logLogin.setTime(time);
        logLogin.setResultInfo(resultInfo);
        logLogin.setMethod(methodName);
        logLogin.setTraceId(traceId);
        this.asyncSaveLog(logLogin);
    }

    /**
     * 异步保存日志信息
     * @param log
     */
    @Async("logAsyncExecutor")
    public void asyncSaveLog(Log log) {
        logService.save(log);
    }
}
